﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ReceiptTracker
{
    public partial class FormEditShop : Form
    {
        ContextMenuStrip strip = new ContextMenuStrip();
        ToolStripMenuItem edit = new ToolStripMenuItem("Edit");
        ToolStripMenuItem delete = new ToolStripMenuItem("Delete");
        private SQLiteDB db;
        private DataTable dt = new DataTable();
        public bool ValuesChanged { get; set; }
        public FormEditShop(SQLiteDB db)
        {
            InitializeComponent();
            this.db = db;
            RefreshView();
            dataGridView.DataSource = dt;
            strip.Items.Add(edit);
            strip.Items.Add(delete);
            edit.Click += new EventHandler(this.edit_Clicked);
            delete.Click += new EventHandler(this.delete_Clicked);
        }

        private void RefreshView()
        {
            db.SQLQuery("SELECT Shops.id,Shops.name,Categories.name AS Category FROM Shops,Categories WHERE Shops.category=Categories.Id;");
            dt.Clear();
            dt.Merge(db.QueryResult);
        }
        private void FormEditShop_Load(object sender, EventArgs e)
        {
            ValuesChanged = false;
        }

        private void dataGridView_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
        {
            e.ContextMenuStrip = strip;
        }
        
        private void edit_Clicked(object sender, EventArgs e)
        {

        }

        private void delete_Clicked(object sender, EventArgs e)
        {
            dataGridView.Rows[dataGridView.SelectedCells[0].RowIndex].Selected = true; //Select the entire row
            if (MessageBox.Show("Do you really want to delete the shop:\n" + dataGridView.SelectedRows[0].Cells["name"].Value +  
                " and all receipts registered to it?", "Delete receipt", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                db.SQLCommand("DELETE FROM Receipts WHERE Shop=" + dataGridView.SelectedRows[0].Cells["id"].Value + ";");
                db.SQLCommand("DELETE FROM Shops WHERE id=" + dataGridView.SelectedRows[0].Cells["id"].Value + ";");
                db.SQLCommand("UPDATE Shops SET id=id-1 WHERE id>" + dataGridView.SelectedRows[0].Cells["id"].Value + ";");
                db.SQLCommand("UPDATE Receipts SET shop=shop-1 WHERE id>" + dataGridView.SelectedRows[0].Cells["id"].Value + ";");
                RefreshView();
                ValuesChanged = true;
            }
        }
    }
}
